// components/product/product-supply-item/index.js
import componentBehavior from '../../../behaviors/component';
import { COMPONENT_OPTIONS } from '../../../constants/common';
import { ACTIVITY_BONUS_RATE } from '../../../constants/activity';
import { formatDecimal, formatInputDecimal } from '../../../common/utils';
import { tipToast } from '../../../common/env';

Component({
    behaviors: [componentBehavior],
    options: {
        ...COMPONENT_OPTIONS,
    },
    properties: {
        productInfo: {
            type: Object,
            value: {},
        },
    },
    observers: {
        'productInfo': function (productInfo) {
            if (productInfo) {
                let { percentOff = '' } = productInfo;
                if (percentOff) percentOff = percentOff / 10;
                const { priceMin, priceMax } = productInfo;
                const hasSkus = priceMin != priceMax;
                const priceStr = `¥ ${priceMin ? priceMin / 100 : priceMin}${hasSkus ? '-' + (priceMax ? priceMax / 100 : priceMax) : ''}`;
                const supplyPriceStr = `¥ ${formatDecimal((priceMin ? priceMin / 100 : priceMin) * percentOff / 100)}${hasSkus ? '-' + formatDecimal(((priceMax ? priceMax / 100 : priceMax)) * percentOff / 100) : ''}`;
                this.setData({ priceStr, supplyPriceStr, percentOff });
            }
        },
    },
    data: {
        price: '',
        percentOff: '',
        supplyPriceStr: '',
    },
    methods: {
        handleChange(e) {
            const { productId } = this.data.productInfo;
            let percentOff = formatInputDecimal(e.detail.value, 1);
            if (percentOff < 0) {
                tipToast('请输入正确的佣金比例');
                return;
            }
            if (percentOff > ACTIVITY_BONUS_RATE) {
                tipToast(`佣金比例最高不超过${ACTIVITY_BONUS_RATE}%`);
                percentOff = '';
            }
            if (percentOff) percentOff = percentOff * 10;
            this.triggerEvent('change', {
                productId,
                percentOff,
            });
        },
    }
})
